package com.xxjqr.rbac.auth;


import cn.hutool.core.util.URLUtil;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 获取url需要的角色列表
 */
@Component
public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private static Map<String, List<ConfigAttribute>> configAttributeMap = null;
    @Resource
    private DynamicSecurityService dynamicSecurityService;
    private final PathMatcher pathMatcher = new AntPathMatcher();

    @PostConstruct
    public void loadDataSource() {
        configAttributeMap = dynamicSecurityService.loadDataSource();
    }

    //当调用了编辑角色资源的function后，清空该缓存
    public void clearDataSource() {
        if (configAttributeMap != null) {
            configAttributeMap.clear();
            configAttributeMap = null;
        }
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {

        // 获取当前请求url
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        String path = URLUtil.getPath(requestUrl);

        if (configAttributeMap == null) {
            this.loadDataSource();
        }
        for (Map.Entry<String, List<ConfigAttribute>> stringListEntry : configAttributeMap.entrySet()) {
            //key就是url路径，value就是该url对应的支持的角色列表
            if (pathMatcher.match(stringListEntry.getKey(), path)) {
                return configAttributeMap.get(stringListEntry.getKey());
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
